package io.gitee.zhangbinhub.acp.cloud.server.helloworld.component;

import com.alibaba.cloud.nacos.balancer.NacosBalancer;
import com.alibaba.cloud.nacos.loadbalancer.LoadBalancerAlgorithm;
import org.jetbrains.annotations.NotNull;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultRequest;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.RequestData;
import org.springframework.cloud.client.loadbalancer.RequestDataContext;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CustomerLoadBalancerAlgorithm implements LoadBalancerAlgorithm {
    @NotNull
    @Override
    public String getServiceId() {
        return DEFAULT_SERVICE_ID;
    }

    @NotNull
    @Override
    public ServiceInstance getInstance(@NotNull Request<?> request, @NotNull List<ServiceInstance> serviceInstances) {
        System.out.println(">>>>>>>> CustomerLoadBalancerAlgorithm");
        RequestData requestData = ((RequestDataContext) ((DefaultRequest<?>) request).getContext()).getClientRequest();
        System.out.println(requestData.getHeaders().toString());
        return NacosBalancer.getHostByRandomWeight3(serviceInstances);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
